package com.bah.tract.client.ui;

import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import java.util.Set;
import java.util.prefs.Preferences;

import javax.inject.Inject;
import javax.swing.JDialog;

import com.atlassian.jira.rpc.soap.client.JiraSoapService;
import com.atlassian.jira.rpc.soap.client.RemoteException;
import com.atlassian.jira.rpc.soap.client.RemoteWorklog;
import com.atlassian.jira_soapclient.SOAPSession;
import com.bah.tract.client.Constants;
import com.bah.tract.client.ErrorHandler;
import com.bah.tract.client.workstore.jira.JiraWork;
import com.bah.tract.client.workstore.jira.JiraWorkStore;
import com.bah.tract.security.PasswordEncryptor;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

@Singleton
public class JiraSubmitDialog extends JDialog implements DataDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2479915347098051557L;

	private final JiraTimePanel panel;

	private final JiraWorkStore mJiraWorkStore;

	private final String user;
	private String password;

	@Inject
	JiraSubmitDialog(@Named("defaultImage") final Image image,
			final JiraWorkStore jiraWorkStore, final Preferences preferences,
			final PasswordEncryptor encryptor) {
		mJiraWorkStore = jiraWorkStore;
		setTitle("TRACT - Jira Time Card");
		panel = new JiraTimePanel();
		setIconImage(image);
		add(panel);
		pack();
		user = preferences.get(Constants.JIRA_ID_PREF, null);
		try {
			password = encryptor.decrypt(preferences.get(
					Constants.JIRA_PASS_PREF, null));
		} catch (final GeneralSecurityException e) {
			ErrorHandler.handleError(e);
		}
	}

	@Override
	public final void setVisible(final boolean b) {
		// Refresh the data in the panel if it is being displayed
		if (b) {
			refresh();
		}
		super.setVisible(b);
	}

	public class JiraTimePanel extends javax.swing.JPanel {

		private final class JiraTimeLogger implements
				java.awt.event.ActionListener {
			@Override
			public void actionPerformed(final java.awt.event.ActionEvent evt) {

				try {

					// Unfortunately each issue could be from a different
					// Jira server. We have to make a fresh connection for
					// each one.
					final Set<JiraWork> work = mJiraWorkStore.getWork();
					for (final JiraWork j : work) {
						final SOAPSession soapSession = new SOAPSession(
								new URL(j.getServiceUrl()));

						soapSession.connect(user, password);

						// the JIRA SOAP Service and authentication token
						// are
						// used to make
						// authentication calls
						final JiraSoapService jiraService = soapSession
								.getJiraSoapService();
						final String authToken = soapSession
								.getAuthenticationToken();

						final RemoteWorklog workLog = new RemoteWorklog();
						workLog.setStartDate(Calendar.getInstance());
						workLog.setTimeSpent(j.getMinutes() + "m");
						workLog.setComment("Automated post from TRACT");
						jiraService
								.addWorklogAndAutoAdjustRemainingEstimate(
										authToken, j.getIssueNumber(),
										workLog);
					}
				} catch (final RemoteException e) {
					ErrorHandler.handleError(e);
				} catch (final MalformedURLException e) {
					ErrorHandler.handleError(e);
				} catch (final java.rmi.RemoteException e) {
					ErrorHandler.handleError(e);
				}

				JiraSubmitDialog.this.setVisible(false);
			}
		}

		/**
	 * 
	 */
		private static final long serialVersionUID = 1L;

		public JiraTimePanel() {
			initComponents();
		}

		// <editor-fold defaultstate="collapsed" desc="Generated Code">
		private void initComponents() {

			jScrollPane1 = new javax.swing.JScrollPane();
			jTable1 = new javax.swing.JTable();
			cancelBtn = new javax.swing.JButton();
			okBtn = new javax.swing.JButton();

			jScrollPane1.setViewportView(jTable1);

			cancelBtn.setText("Cancel");
			cancelBtn.addActionListener(new java.awt.event.ActionListener() {
				@Override
				public void actionPerformed(final java.awt.event.ActionEvent evt) {
					JiraSubmitDialog.this.setVisible(false);
				}
			});

			okBtn.setText("OK");
			okBtn.addActionListener(new JiraTimeLogger());

			final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
					this);
			setLayout(layout);
			layout.setHorizontalGroup(layout
					.createParallelGroup(
							javax.swing.GroupLayout.Alignment.LEADING)
					.addGroup(
							layout.createSequentialGroup()
									.addContainerGap()
									.addGroup(
											layout.createParallelGroup(
													javax.swing.GroupLayout.Alignment.LEADING)
													.addGroup(
															javax.swing.GroupLayout.Alignment.TRAILING,
															layout.createSequentialGroup()
																	.addComponent(
																			okBtn)
																	.addPreferredGap(
																			javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																	.addComponent(
																			cancelBtn))
													.addComponent(
															jScrollPane1,
															javax.swing.GroupLayout.DEFAULT_SIZE,
															380,
															Short.MAX_VALUE))
									.addContainerGap()));
			layout.setVerticalGroup(layout
					.createParallelGroup(
							javax.swing.GroupLayout.Alignment.LEADING)
					.addGroup(
							javax.swing.GroupLayout.Alignment.TRAILING,
							layout.createSequentialGroup()
									.addContainerGap()
									.addComponent(
											jScrollPane1,
											javax.swing.GroupLayout.DEFAULT_SIZE,
											244, Short.MAX_VALUE)
									.addPreferredGap(
											javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
									.addGroup(
											layout.createParallelGroup(
													javax.swing.GroupLayout.Alignment.BASELINE)
													.addComponent(cancelBtn)
													.addComponent(okBtn))
									.addContainerGap()));
		}// </editor-fold>

		// Variables declaration - do not modify
		private javax.swing.JButton cancelBtn;
		private javax.swing.JButton okBtn;
		private javax.swing.JScrollPane jScrollPane1;
		private javax.swing.JTable jTable1;

		// End of variables declaration

		public final void refresh() {
			final Set<JiraWork> work = mJiraWorkStore.getWork();
			final Object[][] data = new Object[work.size()][3];
			int i = 0;
			for (final JiraWork j : work) {
				data[i][0] = j.getIssueNumber();
				data[i][1] = j.getLabel().substring(
						j.getIssueNumber().length() + 1);
				// TODO make this pretty
				data[i][2] = j.getMinutes() + "m";
				i++;
			}
			jTable1.setModel(new javax.swing.table.DefaultTableModel(data,
					new String[] { "Key", "Summary", "Effort" }));
		}
	}

	@Override
	public final void refresh() {
		panel.refresh();
	}
}
